<template>
  <div class="store">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold">商店管理</span>
      </div>
      <!-- 查询表单 -->
      <el-row>
        <el-col :span="24">
          <el-form inline class="query-form">
            <el-form-item label="商店代码">
              <el-input
                v-model="query.storeId"
                placeholder="请输入商店代码"
              ></el-input>
            </el-form-item>
            <el-form-item label="商店名称">
              <el-input
                v-model="query.storeName"
                placeholder="请输入商店名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="商店状态">
              <el-select
                v-model="query.storeStatus"
                placeholder="请选择商店状态"
              >
                <el-option label="开业" value="开业"></el-option>
                <el-option label="停业" value="停业"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="fetchData">查询</el-button>
              <el-button @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <!-- 操作按钮 -->
      <el-row>
        <el-col :span="24">
          <el-button type="success" @click="handleAdd" style="float: left"
            >新增商店</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格展示 -->
      <el-row>
        <el-col :span="24">
          <el-table
            :data="tableData"
            border
            style="width: 100%"
            class="store-table"
          >
            <el-table-column
              prop="storeId"
              label="商店代码"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="storeName"
              label="商店名称"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="createTime"
              label="创建时间"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="storeStatus"
              label="商店状态"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="type"
              label="商店类型"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="storeAddress"
              label="商店地址"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="companyName"
              label="组织名称"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button type="text" @click="handleEdit(scope.row)"
                  >编辑</el-button
                >
                <el-button type="text" @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页组件 -->
      <el-row>
        <el-col :span="24">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </el-col>
      </el-row>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        ref="storeForm"
        :model="storeForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="商店代码">
          <el-input
            v-model="storeForm.storeId"
            placeholder="商店代码"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item label="商店名称" prop="storeName">
          <el-input
            v-model="storeForm.storeName"
            placeholder="请输入商店名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="storeForm.createTime"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="float: left"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="商店状态" prop="storeStatus">
          <el-select v-model="storeForm.storeStatus" style="float: left">
            <el-option label="开业" value="开业"></el-option>
            <el-option label="停业" value="停业"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商店类型" prop="type">
          <el-select v-model="storeForm.type" style="float: left">
            <el-option label="服装" value="服装"></el-option>
            <el-option label="食品" value="食品"></el-option>
            <el-option label="综合" value="综合"></el-option>
            <el-option label="生鲜" value="生鲜"></el-option>
            <el-option label="科技" value="科技"></el-option>
            <el-option label="家电" value="家电"></el-option>
            <el-option label="汽车" value="汽车"></el-option>
            <el-option label="线上服务" value="线上服务"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商店地址" prop="storeAddress">
          <el-input
            v-model="storeForm.storeAddress"
            placeholder="请输入商店地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="组织编码" prop="organizationId">
          <el-select
            v-model="storeForm.organizationId"
            placeholder="请选择组织"
            @change="selectOrganization"
            style="float: left"
          >
            <el-option
              v-for="org in organizations"
              :key="org.organizationId"
              :label="org.organizationId"
              :value="org.organizationId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织名称">
          <el-input v-model="storeForm.companyName" disabled></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStore">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getAllOrganizations } from "@/api/organizationsApi";
import {
  deleteStore,
  storeCreate,
  storeEdit,
  storePageQuery,
} from "@/api/storeApi";
import axios from "axios"; // 引入 Axios

export default {
  name: "AdminStore",
  data() {
    return {
      query: {
        storeId: "",
        storeName: "",
        storeStatus: "",
      },
      tableData: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      dialogVisible: false,
      dialogTitle: "新增商店",
      storeForm: {
        storeId: "",
        storeName: "",
        createTime: "",
        storeStatus: "",
        type: "",
        storeAddress: "",
        organizationId: "",
        companyName: "",
      },
      currentStore: null,
      organizations: [], // 组织信息，从后端获取
      rules: {
        storeName: [
          { required: true, message: "请输入商店名称", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "请选择创建时间", trigger: "change" },
        ],
        storeStatus: [
          { required: true, message: "请选择商店状态", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择商店类型", trigger: "change" },
        ],
        storeAddress: [
          { required: true, message: "请输入商店地址", trigger: "blur" },
        ],
        organizationId: [
          { required: true, message: "请选择组织", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    // 获取商店数据
    fetchData() {
      const params = {
        query: {
          storeId: this.query.storeId,
          storeName: this.query.storeName,
          storeStatus: this.query.storeStatus,
        },
        pageRequestDto: {
          page: this.currentPage,
          size: this.pageSize,
        },
      };

      storePageQuery(params)
        .then((res) => {
          this.tableData = res.data.records;
          this.total = res.data.total;
        })
        .catch((error) => {
          console.error("获取商店数据失败:", error);
          this.$message.error("获取商店数据失败");
        });
    },
    resetQuery() {
      this.query.storeId = "";
      this.query.storeName = "";
      this.query.storeStatus = "";
      this.fetchData();
    },
    handleAdd() {
      this.dialogTitle = "新增商店";
      this.storeForm = {
        storeId: "",
        storeName: "",
        createTime: "",
        storeStatus: "",
        type: "",
        storeAddress: "",
        organizationId: "",
        companyName: "",
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = "编辑商店";
      this.currentStore = row;
      this.storeForm = { ...row };
      this.dialogVisible = true;
    },
    handleDelete(row) {
      this.$confirm(`确定要删除商店 ${row.storeId} 吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteStore(row.storeId)
            .then(() => {
              this.$message.success("删除成功");
              this.fetchData(); // 刷新数据
            })
            .catch((error) => {
              console.error("删除失败:", error);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    saveStore() {
      this.$refs.storeForm.validate((valid) => {
        if (valid) {
          if (this.dialogTitle === "新增商店") {
            storeCreate(this.storeForm)
              .then(() => {
                this.$message.success("新增成功");
                this.fetchData(); // 刷新数据
              })
              .catch((error) => {
                console.error("新增失败:", error);
                this.$message.error("新增失败");
              });
          } else {
            storeEdit(this.currentStore.storeId, this.storeForm)
              .then(() => {
                this.$message.success("编辑成功");
                this.fetchData(); // 刷新数据
              })
              .catch((error) => {
                console.error("编辑失败:", error);
                this.$message.error("编辑失败");
              });
          }
          this.dialogVisible = false;
        } else {
          this.$message.error("表单验证失败，请检查输入信息");
          return false;
        }
      });
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    selectOrganization(organizationId) {
      console.log(this.organizations);
      const org = this.organizations.find(
        (o) => o.organizationId === organizationId
      );
      if (org) {
        this.storeForm.companyName = org.companyName;
      }
    },
    fetchOrganizations() {
       getAllOrganizations()
        .then((res) => {
          this.organizations = res.data;
        })
        .catch((error) => {
          console.error("获取组织信息失败:", error);
          this.$message.error("获取组织信息失败");
        });
    },
  },
  mounted() {
    this.fetchData();
    this.fetchOrganizations(); // 加载组织信息
  },
};
</script>

<style scoped>
.store {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.query-form {
  margin-bottom: 20px;
}

.store-table {
  margin-top: 20px;
}
</style>